package com.cwvs.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cwvs.services.AppUserService;
import com.cwvs.utils.Constant;

public class UserLoginFilter implements Filter {

    public UserLoginFilter() {

    }

    public void destroy() {

    }

    private AppUserService appUserService;

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        if (session.getAttribute(Constant.ADMIN_ID) == null) {
            if("true".equals(req.getParameter("extjs"))){
                res.sendRedirect("/login/extjs");
            }else{
                res.sendRedirect("/");
            }
            return;
        } else {
            Object obj = session.getAttribute(Constant.ADMIN_NAME);
            Map<String,Object> users = appUserService.getAdminUserByMobile((String)obj);
            if (null == users||users.isEmpty()) {
                res.sendRedirect("/");
                return;
            }
//            else if (null != appUsers && !appUsers.getAllowMultiLogin()) {
//                if (StringUtils.isBlank(appUsers.getLastLoginSessionId())
//                        || !appUsers.getLastLoginSessionId().equals(
//                                session.getId())) {
//                    res.sendRedirect("/login");
//                    return;
//                }
//            }
        }
        chain.doFilter(req, res);
    }

    public void init(FilterConfig fConfig) throws ServletException {
    	appUserService = (AppUserService) WebApplicationContextUtils.getWebApplicationContext(fConfig.getServletContext()).getBean(AppUserService.class);
    }

}
